from elftools.elf.elffile import ELFFile
from elftools.elf.enums import ENUM_E_MACHINE
from lib import fatal

class Machine:
    def __init__(self):
        self.entry = 0
        self.pc = 0
        self.gp_regs = [0] * 32 # 32 general regs
        self.memory = bytearray(1024 * 1024)

    def _load_segment(self, segment):
        """
        load elffile's segment to memory
        """
        page_size = 4096
        offset = segment[]



    def machine_load_program(self, file):
        with open(file, "rb") as f_obj:
            magic = f_obj.read(4)
            if magic == b'\x7fELF':
                print("ELF OK")
            else:
                print("ELF  fail")
                return

            # 回到开头重新读取 ELF
            f_obj.seek(0)
            elf = ELFFile(f_obj)

            elfclass = elf.elfclass # 32 or 64
            endian = elf.little_endian # true or false
            arch = elf['e_machine']

            print(f"ELF Class       : {elfclass}-bit")
            print(f"Endian          : {'Little' if endian else 'Big'} Endian")
            print(f"Machine Arch    : {arch}")

            # 获取入口地址
            self.entry = elf.header['e_entry']
            self.pc = self.entry
            print(f"Entry point     : 0x{self.entry:x}")

            for segment in elf.iter_segments():
                print(f"Loading segment: {segment.header}")
                if segment["p_type"] == "PT_LOAD":
                    print("KK")

